package com.zat.mes.andrmes.base

import android.app.ActivityManager
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.customerview.LoadingDialog
import com.zat.mes.andrmes.customerview.LoadingDialog.Companion.closeLoading
import com.zat.mes.andrmes.dofun.system.LoginActivity
import com.zat.mes.andrmes.event.LoadingEventMessage
import com.zat.mes.andrmes.event.TokenEventMessage
import com.zat.mes.andrmes.utils.ActivityUtils
import com.zat.mes.andrmes.utils.StatusBarUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @author zy
 * @date :2020-02-04 15:03
 * @description:父activity
 */
abstract class BaseActivity : AppCompatActivity() {
    /**
     * 通用loading
     */
    protected var loadingDialog: Dialog? = null
    /**
     * 主布局
     */
    var contentView: FrameLayout? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//强制竖屏
        ActivityUtils.put(this)
        setStatusBar()
        EventBus.getDefault().register(this);
        init();
        Log.e("activity==", this.javaClass.simpleName)
    }

    /**
     * 通用初始化
     */
    abstract protected fun init();

    override fun setContentView(layoutResID: Int) {
        contentView =
            LayoutInflater.from(this).inflate(R.layout.layout_content_view, null) as FrameLayout
        val activityView = LayoutInflater.from(this).inflate(layoutResID, null)
        contentView?.addView(activityView, 0)
        setContentView(contentView)
//        super.setContentView(layoutResID)
    }

    /**
     * 设置空布局
     */
    fun setEmptyVisible() {
        contentView?.findViewById<TextView>(R.id.tvEmptyContent)?.visibility = View.VISIBLE
    }

    /**
     * 隐藏恐怖剧
     */
    fun setEmptyGone() {
        contentView?.findViewById<TextView>(R.id.tvEmptyContent)?.visibility = View.GONE
    }

    open protected fun setStatusBar() {
        //清单文件中要设置主题为NoActionBar
        val drawable = resources.getDrawable(R.drawable.dw_statusbar)
        StatusBarUtils.with(this).setDrawable(drawable).init()
    }

    /**
     * 登录过期
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onMessageEvent(event: TokenEventMessage?) { /* Do something */
        //token 失效
        if (isForeground()) {
            if(TextUtils.isEmpty(event?.message)){
                val builder = AlertDialog.Builder(this)
                    .setMessage(getString(R.string.logout_force))
                    .setPositiveButton(
                        getString(R.string.sure),
                        DialogInterface.OnClickListener { dialog, which ->
                            val intent = Intent(this, LoginActivity::class.java)
                            startBaseActivity(intent)
                            Handler().postDelayed(
                                Runnable { ActivityUtils.finishWithoutTop() },
                                500
                            )
                        })
                val show = builder.show()
                show.setCancelable(false)
            }else{
                val intent = Intent(this, LoginActivity::class.java)
                startBaseActivity(intent)
                Handler().postDelayed(Runnable { ActivityUtils.finishWithoutTop() }, 500)
            }
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onLoadingEvent(event: LoadingEventMessage?) { /* Do something */
        closeLoading()
    }

    /**
     * 关闭loading
     */
    open fun closeLoading() {
        loadingDialog?.let { LoadingDialog.closeLoading(it) }
    }

    /**
     * 开启loading
     */
    open fun showLoading() {
        if (loadingDialog == null) {
            loadingDialog = LoadingDialog.createLoading(this)
        } else {
            loadingDialog?.show()
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy()
    }

    override fun finish() {
        ActivityUtils.remove(javaClass.name)
        super.finish()
    }

    /**
     * 启动activity
     */
    open fun startBaseActivity(intent: Intent) {
        try {
            startActivity(intent)
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }

    }

    /**
     * 判断某个界面是否在前台
     */
    open fun isForeground(): Boolean {
        val className = javaClass.name
        if (baseContext == null || TextUtils.isEmpty(className)) {
            return false
        }
        val am = baseContext
            .getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val list = am.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val cpn = list[0].topActivity
            if (className == cpn!!.className) {
                return true
            }
        }
        return false
    }


}